<?php defined('SYSPATH') or die('No direct script access.');

class Attribute_Controller extends Template_Controller 
{
	public function __construct()
	{
		parent::__construct();

		$auth = new Auth();
		
		if (!$auth->logged_in())
		{
			url::redirect('auth/login', 301);
			exit;
		}
		
		// Add the menu to the template
		$this->template->menu = new View('menu');
	}
	
	public function index()
	{		
		$model = new Attribute_Model();
		$attribute = $model->find_all();
		
		$table = new View('product/attribute_lists');
		$table->caption = 'Attribute List';
		$table->datas = $attribute;
		
		$this->template->content = $table->render();
	}
	
	public function create()
	{
		$form = new Forge(NULL, 'New Attribute');
		$form->input('name')->label(TRUE);
		$form->input('title_cn')->label('Chinese Title')->rules('required');
		$form->input('title_en')->label('English Title')->rules('required');
		$form->submit('Save');
 
		if($form->validate())
		{
			//Load model and set values
			$attribute = new Attribute_Model();
			$attribute->name = trim($form->name->value) == '' ? $form->title_cn->value : $form->name->value;
			$attribute->title_cn = $form->title_cn->value;
			$attribute->title_en = $form->title_en->value;
 
			//Save form into table
			if($attribute->save())
			{
				url::redirect('attribute');
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
		    $this->template->content = $form->render();
		}
	}
	
	public function edit($id)
	{
		$attribute = new Attribute_Model($id);

		$form = new Forge(NULL, 'Edit Attribute');
		$form->input('name')->label(TRUE)->value($attribute->name);
		$form->input('title_cn')->label('Chinese Title')->rules('required')->value($attribute->title_cn);
		$form->input('title_en')->label('English Title')->rules('required')->value($attribute->title_en);
		$form->submit('Save');
 
		if($form->validate())
		{
			$attribute->name = $form->name->value;
			$attribute->title_cn = $form->title_cn->value;
			$attribute->title_en = $form->title_en->value;
 
			//Save form into table
			if($attribute->save())
			{
				url::redirect('attribute');
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
		    $this->template->content = $form->render();
		}
	}
	
	public function delete($id)
	{
		$attribute = new Attribute_Model($id);
		$attribute->delete();
		
		url::redirect('attribute');
	}
}